package com.hequ.merchant.banner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.hequ.merchant.banner.ApplicationHelper;
import com.hequ.merchant.banner.BuildConfig;
import com.hequ.merchant.banner.R;
import com.hequ.merchant.banner.api.BannerAddRequest;
import com.hequ.merchant.banner.api.ModuleDataListLoader;
import com.hequ.merchant.banner.api.OnRequestListener;
import com.hequ.merchant.banner.api.SimpleRequestListener;
import com.hequ.merchant.banner.entity.Banner;
import com.hequ.merchant.banner.entity.Module;
import com.hequ.merchant.banner.util.AppConstant;
import com.hequ.merchant.banner.util.CropImageUtil;
import com.hequ.merchant.banner.util.NetworkImageUtil;
import com.hequ.merchant.banner.util.PostUtil;
import com.hequ.merchant.banner.util.Toasts;
import com.hequ.merchant.banner.util.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_ACTION;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_BACKGROUND;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_ENABLED;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_ID;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_IMAGENAME;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_MEMO;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_NAME;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_POSITION;
import static com.hequ.merchant.banner.handler.BannerJsonResponseHandler.JSON_KEY_URL;


/**
 * Created by 柯尊诚 on 2015/10/21.
 * kzc
 */
public class AddBannerActivity extends Activity {

    private int actionCode = 100;
    private EditText titleFiled;
    private EditText colorFiled;
    private EditText positionFiled;
    private Spinner actionSp;
    private RadioGroup enabledRg;
    private EditText memoFiled;
    private EditText urlFiled;
    private Button selectBtn;
    private Button subumitBtn;
    private Button selectModuleBtn;
    private ImageView fileImage;
    private ArrayList<Banner.Action> actions = new ArrayList<>();
    private ArrayAdapter<Banner.Action> adapter;

    private String titleValues;
    private String colorValues;
    private String positionValues;
    private String memoValues;
    private String urlValues;
    private String actionValues;
    private String imageNameValues;
    private int enabledValues = 0;

    private RequestQueue requestQueue;

    private String bannerId = null;
    public static boolean isChange = false;
    public List<Module> modules = new ArrayList<>();

    private Uri imageUri;
    private final int CHOOSE_BIG_PICTURE = 5;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.banner_add);

        init();

        selectAction();
        selectEnabled();
        requestQueue = Volley.newRequestQueue(this);

        if (isChange) {
            changeInfo();
        }
    }

    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";

    /**
     * 初始化组件
     */
    private void init() {
        titleFiled = (EditText) findViewById(R.id.et_title);
        colorFiled = (EditText) findViewById(R.id.et_color);
        positionFiled = (EditText) findViewById(R.id.et_position);
        actionSp = (Spinner) findViewById(R.id.sp_action);
        enabledRg = (RadioGroup) findViewById(R.id.rg_enabled);
        memoFiled = (EditText) findViewById(R.id.et_memo);
        urlFiled = (EditText) findViewById(R.id.et_url);
        selectBtn = (Button) findViewById(R.id.btn_select);
        subumitBtn = (Button) findViewById(R.id.btn_submit);
        fileImage = (ImageView) findViewById(R.id.iv_file);
        selectModuleBtn = (Button) findViewById(R.id.btn_moduleid);

        imageUri = Uri.parse(IMAGE_FILE_LOCATION);
        selectBtn.setOnClickListener(selectImage);
        subumitBtn.setOnClickListener(subumitInfo);

        selectModuleBtn.setOnClickListener(selectModule);

//        TextWatcher textChangedListener = new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
////                Log.d("xxx1", s.toString());
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
////                Log.d("xxx2", s.toString());
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                Log.d("xxx3",s.toString());
//                if (!MatchUrl(s.toString())){
//                    Toasts.makeText("不符合规范，请重新输入");
//                }
//            }
//        };
//        urlFiled.addTextChangedListener(textChangedListener);
    }

    private OnClickListener selectModule = new OnClickListener() {
        @Override
        public void onClick(View v) {
            selectModuleDiaglog();
        }
    };

    /**
     * 修改信息
     */
    public void changeInfo() {
        Log.d("xxxx", "开始修改信息");
        Banner banner = (Banner) getIntent().getSerializableExtra("banner");
        titleFiled.setText(banner.getName());
        colorFiled.setText(banner.getBackGround());

        urlFiled.setText(banner.getUrl());
        memoFiled.setText(banner.getMemo());
        //勾选模块
        modules = banner.getModules();
        //显示本地缓存图片,文件不存在访问网络
        String imagePath = Environment.getExternalStorageDirectory().getPath() + "/hequ/" + banner.getImageName();

        if (new File(imagePath).exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            fileImage.setImageBitmap(bitmap);
        } else {
            NetworkImageUtil.getInstance(this).loadImageByVolley(banner.getImage(), fileImage);
        }
        imageNameValues = banner.getImageName();
        bannerId = banner.getId();
    }

    /**
     * 点击提交数据事件
     */
    private OnClickListener subumitInfo = new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (!MatchUrl(urlFiled.getText().toString().trim())){
                Toasts.makeText("URL不符合规范，请重新输入");
                urlFiled.requestFocus();
            } else {
                requestQueue.start();
                requestQueue.add(new BannerAddRequest(listener));
            }
        }
    };

    /**
     * 获取表单数据
     */
    private void getValues() {
        titleValues = titleFiled.getText().toString().trim();
        positionValues = positionFiled.getText().toString().trim();
        colorValues = colorFiled.getText().toString().trim();
        urlValues = urlFiled.getText().toString().trim();
        memoValues = memoFiled.getText().toString().trim();
    }

    /**
     * 模块多选框
     *
     * @return
     */
    private Dialog selectModuleDiaglog() {

        int length = ApplicationHelper.getModules().size();

        final String[] items = new String[length];

        final boolean[] flags = new boolean[length];

        for (int i = 0; i < length; i++) {
            items[i] = ApplicationHelper.getModules().get(i).getName();

                for (int j = 0; j < modules.size(); j++) {
                    if (modules.get(j).getId().equals(ApplicationHelper.getModules().get(i).getId())) {
                        flags[i] = true;

                        break;
                    } else {
                        flags[i] = false;
                    }
                }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("模块多选");
        builder.setMultiChoiceItems(items, flags, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                Log.d("xxwhich", which + "!!!" + isChecked + "###" + flags[which]);
                if (isChecked) {
                    modules.add(ApplicationHelper.getModules().get(which));
                } else {
                    modules.remove(ApplicationHelper.getModules().get(which));
                }
                Log.d("xxmodules", modules.toString() + "");

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                modules.clear();
            }
        }).show();

        Dialog dialog = builder.create();

        return dialog;
    }


    /**
     * 选择动作
     */
    private void selectAction() {

//        list.add("web: 跳转到网页");
//        list.add("self: 在当前应用中打开");
//        list.add("app: 打开外部应用");
//        list.add("browser: 在浏览器打开");
//        list.add("none: 无点击效果");

        actions.add(Banner.Action.web);
        actions.add(Banner.Action.self);
        actions.add(Banner.Action.app);
        actions.add(Banner.Action.browser);
        actions.add(Banner.Action.none);

        adapter = new ArrayAdapter<Banner.Action>(this, android.R.layout.simple_spinner_item, actions);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        actionSp.setAdapter(adapter);
        actionSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //String action = list.get(position);
                //action = action.substring(0, action.indexOf(": "));
                //Toast.makeText(AddBannerActivity.this, action, Toast.LENGTH_SHORT).show();

                Banner.Action action = actions.get(position);
                actionValues = action.value;
                Toasts.makeText("你选择" + position + "了：" + actionValues);
                if (position == 3) {
                    //browser
                    actionCode = 3;
                }
                if (position == 1) {
                    //sef
                    actionCode = 1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


    public boolean MatchUrl(String text) {
        Log.d("xxaction", actionCode+"");
        Pattern p = null;
        if (actionCode == 3)
            p = Pattern.compile("^http://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(/(\\w+))*(\\w*\\.)*(\\w*)*", Pattern.CASE_INSENSITIVE);
        if (actionCode == 1)
            p = Pattern.compile("trk://merchant/(\\w+)(\\?)(\\w)*(\\=)(.*)");
        if (actionCode == 100)
            return true;
        Matcher matcher = p.matcher(text);
        Log.d("xxaction", matcher.matches() + "");
        return matcher.matches();
    }


    /**
     * 选择是否可用
     */
    private void selectEnabled() {
        enabledRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int rgId = group.getCheckedRadioButtonId();
                RadioButton rb = (RadioButton) AddBannerActivity.this.findViewById(rgId);
                if (rb.getText().equals("可用")) {
                    enabledValues = 0;
                } else {
                    enabledValues = 1;
                }
            }
        });
    }


    /**
     * 选择图片
     */
    private OnClickListener selectImage = new OnClickListener() {
        @Override
        public void onClick(View v) {
        Utils.getInstance().selectPicture(AddBannerActivity.this);
//            CropImageUtil.getInstance().cropPicture(AddBannerActivity.this, imageUri, CHOOSE_BIG_PICTURE);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {//result is not correct
            return;
        }
        if (null == data) {
            return;
        }
        Uri uri = null;
        if (requestCode == AppConstant.KITKAT_LESS) {//<19
            uri = data.getData();
            Log.d("tag1", "uri= " + uri);
            //调用裁切方法
            Utils.getInstance().cropPicture(AddBannerActivity.this, imageUri);
        } else if (requestCode == AppConstant.KITKAT_ABOVE) {//>19
            uri = data.getData();
            Log.d("tag2", "uri= " + uri);
            //先将这个uri转换成path，然后再转换成uri
            String thePath = Utils.getInstance().getPath(this, uri);
            //调用裁切方法
//            Utils.getInstance().cropPicture(AddBannerActivity.this, Uri.fromFile(new File(thePath)));
            Utils.getInstance().cropPicture(AddBannerActivity.this, imageUri);
        } else if (requestCode == AppConstant.INTENT_CROP) {
//            Toast.makeText(this, "data: " + imageUri, Toast.LENGTH_LONG).show();
            Bitmap bitmap = decodeUriAsBitmap(imageUri);
//            Bitmap bitmap = data.getParcelableExtra("data");
            Log.d("tag3", "bitmap= " + bitmap);
//            if(bitmap == null) {
//                try {
//                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

            File temp = new File(Environment.getExternalStorageDirectory().getPath() + "/hequ/");//自己缓存文件夹
            if (!temp.exists()) {
                temp.mkdir();
            }
            imageNameValues = Calendar.getInstance().getTimeInMillis() + ".jpg";
            String filePath = temp.getAbsolutePath() + "/" + imageNameValues;
            File tempFile = new File(filePath);//以时间秒为文件名
            //图片保存到文件中
            FileOutputStream foutput = null;
            try {
                foutput = new FileOutputStream(tempFile);

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, foutput);
                //上传图片
                upload(filePath);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            fileImage.setImageBitmap(bitmap);

            //重新获取模块列表
            if (ApplicationHelper.getModules().isEmpty())
                ModuleDataListLoader.getInstance(this).getList();
        }


    }

    /**
     * uri转Bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }


    /**
     * 20151010 上传图片 OK
     *
     * @param filePath
     */
    private void upload(final String filePath) {
//        final String SERVER_URL = "http://192.168.0.113:8080/LoadImag/uploadFile";
        final String SERVER_URL = AppConstant.BASE_USL + "/banners/file?token=hequ";
        new Thread() {
            @Override
            public void run() {
                super.run();
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("userId", "0123456789");
                PostUtil.postImg(AddBannerActivity.this, SERVER_URL, filePath, params);
            }
        }.start();

    }


    public void showBannerDialog(String Message) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(Message)
                .setPositiveButton("确定", null)
                .show();
    }

    /**
     * 网络请求，提交数据
     */
    private OnRequestListener<String> listener = new SimpleRequestListener<String>() {

        @Override
        public void onSuccess(String data) {
            AddBannerActivity.this.onNetSuccess(data);
        }

        @Override
        public void onFailed() {
            AddBannerActivity.this.onNetFailed();
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> params = super.getParams();
            params.putAll(onNetGetParams());
            Log.d("params: ", params + "");
            return params;
        }
    };

    public void onNetSuccess(String data) {
        showBannerDialog("提交成功！");
        finish();
    }

    public void onNetFailed() {
        Toasts.makeText("提交失败！");
    }

    public Map<String, String> onNetGetParams() {
        Map<String, String> params = new IdentityHashMap<>();
        //获取表单数据
        getValues();

        params.put(JSON_KEY_NAME, titleValues);
        params.put(JSON_KEY_ACTION, actionValues);
        params.put(JSON_KEY_ENABLED, enabledValues + "");

        if (!TextUtils.isEmpty(imageNameValues))
            params.put(JSON_KEY_IMAGENAME, imageNameValues);
        if (!TextUtils.isEmpty(colorValues))
            params.put(JSON_KEY_BACKGROUND, colorValues);
        if (!TextUtils.isEmpty(positionValues))
            params.put(JSON_KEY_POSITION, positionValues);
        if (!TextUtils.isEmpty(urlValues))
            params.put(JSON_KEY_URL, urlValues);
        if (!TextUtils.isEmpty(memoValues))
            params.put(JSON_KEY_MEMO, memoValues);
        for (int i = 0; i < modules.size(); i++) {
            params.put(new String("moduleId"), modules.get(i).getId());
        }
        if (!TextUtils.isEmpty(bannerId)) {
            params.put(JSON_KEY_ID, bannerId);
        }

        return params;
    }
}
